package com.breaktian.assemble.eventbus;

import android.text.TextUtils;


import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * Created by breaktian on 2016/10/26.
 *
 * 所有的事件注册在这一个类里面
 * 统一处理回调
 * activity/fragment/...只需要实现EventCallBack接口  然后在activity的oncreate方法调用register(this)方法即可
 * 事件调度者
 */

public class EventDispatcher {

    private static EventDispatcher instance;

    private ArrayList<EventCallBack> callBacks;

    private EventDispatcher(){
        EventHelper.get().register(this);//注册到这里
        callBacks = new ArrayList<EventCallBack>();
    }


    public static EventDispatcher get(){
        if(instance==null){
            synchronized (EventDispatcher.class){
                if(instance==null){
                    instance = new EventDispatcher();
                }
            }
        }
        return instance;
    }


    public void register(EventCallBack callBack){
        if(!callBacks.contains(callBack)){
            callBacks.add(callBack);
        }
    }

    public void unregister(EventCallBack callBack){
        if(callBacks.contains(callBack)){
            callBacks.remove(callBack);
        }
    }

    public void post(String type, Object... data){
        if (isEmpty(type)) {
            throw new IllegalArgumentException("Type must not be empty");
        }

        if (data.length % 2 != 0) {
            throw new IllegalArgumentException("Data must be a valid list of key,value pairs");
        }

        Event event = new Event(type);
        int i = 0;
        while (i < data.length) {
            String key = (String) data[i++];
            Object value = data[i++];
            event.put(key,value);
        }

        EventHelper.get().post(event);





    }



    private boolean isEmpty(String type) {
        return TextUtils.isEmpty(type);
    }




    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false, priority = 0)
    public void dispatchAction(Event event) {
        for (EventCallBack call:callBacks) {
            if(call!=null){
                call.onEvent(event);
            }
        }

    }





}
